(function(window){
    "use strict";
	var callbacks = new Map();
    var u = {};
	var socketUrl = "youdelu.fun:10001";
	//var socketUrl = "192.168.3.106:8080";
	//var socketUrl = "127.0.0.1:8080";
	var socket;
	var conncet = false;
	u.isConnect = function(){
		return conncet;
	}
	/**
	 * 初始化
	 * @param {*} fn 
	 */
	u.init = function(fn){
		try{
			socket = io("ws://"+socketUrl,{withCredentials: true});
			socket.on('connect', function() {
				conncet = true;
				fn&&fn(true,"已连接"); 
				//连接成功后将发送失败的重新发送
				if(errSend.size>0){
					errSend.forEach((value, key) => {
					   u.reSend(value);
					}); 
					errSend.clear();
				} 
			});
			socket.on('connecting', function() {
				conncet = false;
				fn&&fn(false,"正在连接..."); 
			});
			socket.on('disconnect', function() {
				conncet=false;
				fn&&fn(false,"断开连接"); 
			});
			socket.on('connect_failed', function() {
				conncet = false;
				fn&&fn(false,"连接失败"); 
			});
			socket.on('error', function() {
				conncet = false;
				fn&&fn(false,"连接出错"); 
			});
			socket.on('reconnect_failed', function() {
				conncet = false;
				fn&&fn(false,"重连失败"); 
			});
			socket.on('reconnect', function() {
				conncet = true;
				fn&&fn(true,"已连接"); 
			});
			socket.on('reconnecting', function() {
				conncet = false;
				fn&&fn(false,"正在重连..."); 
			});
		}catch(e){
			conncet = false;
			fn&&fn(false,"连接出错:"+e); 
		}
	}
	/**
	 * 监听消息
	 * @param {Object} fn
	 */
	u.message = function(fn){
		if(!socket){
			console.log("请先调用init方法");
			return;
		}
		socket.on('message',function(data){ 
			 if(data.action){
				 if(callbacks.size>0&&callbacks.has(data.action)){
					 //有回调的走回调
					 var callback = callbacks.get(data.action); 
					 var d = {};
					 d.status = true;
					 d.res = data;  
					 callback(d);
					 if(data.complete){
						callbacks.delete(data.action);
					 }
					 return;
				 }
			 }
		     fn&&fn(data);
		});
	}
	var errSend = new Map();
	/**
	 * 发送消息
	 * 回调方法在括号里能触发多次回调
	 * 回调方法用then只能触发一次回调
	 * @param {Object} data
	 */
	u.send = function(request,fn){ 
		var action = request.url;
		var param = request.queryData;
		var promise;
		if(fn){ 
			callbacks.set(action,fn); 
		}else{
			promise = new Promise((resolve, reject) => {
				callbacks.set(action,resolve); 
			}); 
		}
		if(!socket){  
			errSend.set(action,request);
			return promise;
		}
		if(!conncet){   
			u.delayedReturnError(action,"未连接成功,取消发送"); 
			return promise;
		}
		var data = {};
		data.action = action;
		if(param){
			data.param = param;
		}
		var s = socket.emit('server_message', JSON.stringify(data));
		if(s.id){ 
			console.log(s.id);
			console.log(data);
			return promise;
		}else{   
			 u.delayedReturnError(action,"发送失败"); 
			 return promise;
		}
	}
	u.reSend=function(request){
		var action = request.url;
		var param = request.queryData;
		var data = {};
		data.action = action;
		if(param){
			data.param = param;
		}
		var s = socket.emit('server_message', JSON.stringify(data));
		if(s.id){
			console.log("发送成功,id="+s.id);
			console.log(data);   
		} 
	}
	/**错误信息回显
	 * @param {Object} action
	 * @param {Object} msg
	 */
	u.delayedReturnError = function(action,msg){	 
		setTimeout(function(){
			if(callbacks.size>0&&callbacks.has(action)){
				 //有回调的走回调
				 var callback = callbacks.get(action);
				 var d = {};
				 d.status = false;
				 d.res = msg; 
				 callback(d); 
				 callbacks.delete(action);
			}
		},0);
	}
	var uzStorage = function(){
	    try {
	        return window.localStorage;
	    }catch (e) {
	
	    }
	   return false ;
	};
	u.setStorage = function(key, value,fn){
	    if(arguments.length === 2||arguments.length === 3){
	        var ls = uzStorage();
	        if(ls){
	            var v = value;
	            if(typeof v == 'object'){
	                v = JSON.stringify(v);
	                v = 'obj-'+ v;
	            }else{
	                v = 'str-'+ v;
	            }
	            ls.setItem(key, v);
	        } 
	    }
	};
	//获取记录
	u.getStorage = function(key,fn){
	    var ls = uzStorage();
	    if(ls){
	        var v = ls.getItem(key);
	        if(!v){return;}
	        if(v.indexOf('obj-') === 0){
	            v = v.slice(4);
	            return JSON.parse(v);
	        }else if(v.indexOf('str-') === 0){
	            return v.slice(4);
	        }
	    } 
	};
	//删除记录
	u.rmStorage = function(key,fn){
	    var ls = uzStorage();
	    if(ls){
	        if(key){
	            ls.removeItem(key);
	        }
	    } 
	};
	window.$socket = u;
})(window);